#-*- coding: utf-8 -*-

import hashlib
from utils import to_str, to_utf8
from bottle import redirect
from session import get_session
from config import cookie_publickey

_publickey = cookie_publickey

class CookieUser(object):
	
	def __init__(self, request=None, response=None):
		self.request = request
		self.response = response
	
	@property
	def uid(self):
		if self.request is not None:
			if self.request.COOKIES.has_key('uid'):
				try:
					return int(self.request.COOKIES['uid'])
				except:
					pass
		return 0
	
	@property
	def username(self):
		if self.request is not None:
			if self.request.COOKIES.has_key('uname'):
				return to_utf8(self.request.COOKIES['uname'])
		return ''
	
	@property
	def authenticated(self):
		if self.uid>0 and len(self.username)>0:
			client_hash = self.request.COOKIES.get('hash') or ''
			hashtext = hashlib.md5('%s\n%s\n%s' % (to_str(self.uid), to_str(self.username), _publickey)).hexdigest()
			return client_hash == hashtext
		return False

	@property
	def isroot(self):
		if self.authenticated and self.request is not None:
			session = get_session(self.request)
			isroot = session.get('isroot')
			# print session
			return isroot
		return False
	
	@isroot.setter
	def isroot(self, value):
		if self.request is not None:
			session = get_session(self.request)
			session['isroot'] = value
			session.save()
			# print 'set isroot=%s' % value
	
	def save(self, uid, username, keep=False):
		if self.response is not None:
			hashtext = hashlib.md5('%s\n%s\n%s' % (to_str(uid), to_str(username), _publickey)).hexdigest()
			cookielifelen = 3600 * 24 * 14 # 2 weeks
			values = {'uid':'%s' % uid, 'uname': to_str(username), 'hash': hashtext}
			if keep:
				set_value = lambda (k,v): self.response.set_cookie(k, v, path='/', max_age=cookielifelen)
			else:
				set_value = lambda (k,v): self.response.set_cookie(k, v, path='/')
			map(set_value, [(k,v) for k,v in values.iteritems()])
	
	def clear(self):
		if self.response is not None:
			self.response.set_cookie('uid', '', path='/')
			self.response.set_cookie('uname', '', path='/')
			self.response.set_cookie('hash', '', path='/')
	
	def __str__(self):
		return self.username

class AuthenticationMiddleWare(object):
	''''''
	def __init__(self, app):
		self.app = app
	
	def __call__(self, e, h):
		return self.app(e, h)

def authorized_only(request, need_root=False):
	'''this is a decorator.'''
	# request.user = CookieUser(request=request)
	def handler_gen(view_func):
		def handler(*args, **kargs):
			user = CookieUser(request=request)
			if not user.authenticated:
				return redirect('/admin/signout/') #'Access denied.'
			elif need_root:
				if not user.isroot:
					return redirect('/admin/need_authorization/')
			return view_func(*args, **kargs)
		return handler
	return handler_gen
	



